package com.lvs.zmwz.controller.admin;
import com.lvs.zmwz.config.WebResource;
import com.lvs.zmwz.exception.MyException;
import com.lvs.zmwz.util.ResultView;
import com.lvs.zmwz.util.UploadFileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * 文件上传
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/file")
public class FileController {

    @Autowired
    protected WebResource webResource;

    /**
     * 文件上传
     *
     * @param file     文件流
     * @param fileName 文件夹名称
     */
    @PostMapping({"/upload", "/admin/upload"})
    public ResultView appFileUpload(@RequestParam("file") MultipartFile[] file,
                                    @RequestParam(value = "fileName", required = false, defaultValue = "files") String fileName) throws MyException {
        return ResultView.ok(UploadFileUtil.flowUpload(file, webResource.getStaticResourcePath(), fileName));
    }

    /**
     * 文件统一删除
     *
     * @param file 文件路径
     */
    @DeleteMapping({"/front/del", "/admin/del"})
    public ResultView delFile(@NotBlank(message = "文件不能为空") String file) {
        return ResultView.ok(UploadFileUtil.deleteFile(webResource.getStaticResourcePath(), webResource.getProjectPath(), file));
    }


    /**
     * 平台实现更新包下载
     ** @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/download")
    public void downloadFile(HttpServletResponse response, String fileFullName) throws UnsupportedEncodingException {
        File file = new File("/home/wwwroot/vcan/uploads/indexPic/20211019/1634646329943.png");
        String fileName = file.getName(); //下载的文件名
        // 如果文件名存在，则进行下载
        if (file.exists()) {
            // 配置文件下载
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("Download the song successfully!");
            } catch (Exception e) {
                System.out.println("Download the song failed!");
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {//对应文件不存在
            try {
                //设置响应的数据类型是html文本，并且告知浏览器，使用UTF-8 来编码。
                response.setContentType("text/html;charset=UTF-8");
                //String这个类里面， getBytes()方法使用的码表，是UTF-8，  跟tomcat的默认码表没关系。 tomcat iso-8859-1
                String csn = Charset.defaultCharset().name();
                System.out.println("默认的String里面的getBytes方法使用的码表是： " + csn);
                //1. 指定浏览器看这份数据使用的码表
                response.setHeader("Content-Type", "text/html;charset=UTF-8");
                OutputStream os = response.getOutputStream();

                os.write("对应文件不存在".getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
